package com.jcl.recruit.api.resume.controller;

import com.jcl.core.resp.ApiResponse;
import com.jcl.recruit.common.service.CommonService;
import com.jcl.recruit.resume.model.*;
import com.jcl.recruit.resume.service.*;
import com.jcl.recruit.user.model.UserOtherjob;
import com.jcl.recruit.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 刘明新
 * @date 2018/8/3 上午9:49
 */
@RestController
@RequestMapping("/api")
public class ResumeBaseController {

    private static Logger log = LoggerFactory.getLogger(RestController.class);

    @Autowired
    private ResumeBaseService resumeBaseService;

    @Autowired
    private ResumeWorkService resumeWorkService;

    @Autowired
    private ResumeEduService resumeEduService;

    @Autowired
    private ResumeProjectService resumeProjectService;

    @Autowired
    private ResumeOrigService resumeOrigService;

    @Autowired
    private UserService userService;


    /**
     * 新增简历
     *
     * @param result)
     * @return
     */
    @RequestMapping(value = "/resume/save", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Map<String, Object> resumeAdd(@RequestBody Map<String, String> result) {
        Map<String, Object> map = new LinkedHashMap<>();
        Resume resume = new Resume();
        Resume entity = resumeBaseService.countNameAndMobile(result.get("realname"), result.get("mobile"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        resume.setUpdatetime(new Date());
        resume.setApplyPosition(result.get("apply_position"));
        resume.setBirthday(result.get("birthday") == null ? null : sdf.parse(result.get("birthday"), new ParsePosition(0)));
        resume.setCurrentAddress(result.get("current_address"));
        resume.setCurrentCity(result.get("current_city"));
        resume.setEduLastEducation(result.get("edu_last_education"));
        resume.setEmail(result.get("email"));
        resume.setEduLastMajor(result.get("major"));
        resume.setMobile(result.get("mobile"));
        resume.setRealname(result.get("realname"));
        resume.setRemark(result.get("remark"));
        resume.setEduLastSchool(result.get("school"));
        resume.setSex(result.get("sex"));
        resume.setSourceSub(result.get("source_sub"));
        resume.setApplyOtherJid(result.get("apply_other_jid"));
        resume.setStatus(StringUtils.isNotBlank(result.get("status")) ? Integer.valueOf(result.get("status")) : null);
        resume.setTags(result.get("tag"));
        resume.setWorkIndustry(result.get("work_industry"));
        resume.setWorkyear(StringUtils.isBlank(result.get("workyear")) ? null : Integer.valueOf(result.get("workyear")));
        resume.setApplyDate(result.get("apply_date") == null ? null : sdf.parse(result.get("apply_date"), new ParsePosition(0)));
        resume.setUpdateDate(new Date());
        resume.setId(StringUtils.isBlank(result.get("id")) ? null : Integer.valueOf(result.get("id")));
        String token = result.get("token");
        String externalMsg = result.get("external_msg");
        if (entity == null && resume.getId() == null) {
            if (userService.selectPrimaryKeyByToken(token) != null) {
                resume.setApplyOtherJid(resume.getSourceSub() + "_" + new Date().getTime());
                UserOtherjob userOtherjob = new UserOtherjob();
                userOtherjob.setOtherJid(resume.getApplyOtherJid());
                userOtherjob.setUserId(Integer.valueOf(userService.selectPrimaryKeyByToken(token).get("id").toString()));
                resumeBaseService.insertOtherjob(userOtherjob);
            }
            resume.setIsmanual(1);
            resume.setCreatetime(resume.getUpdatetime());
            resumeBaseService.insert(resume);

            // 添加日志
            //applyResumeLog.addResumeLog(resume.getId(), ResumeType.TYPE_RESUME_ADD);

        } else {
            resume.setId(entity == null ? resume.getId() : entity.getId());
            resumeBaseService.updateByPrimaryKeySelective(resume);
        }

        map.put("type", "success");
        map.put("message", "执行成功");
        map.put("resume", resume);
        map.put("code", 200);
        return map;
    }

    /**
     * 更新简历状态
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/resume/status/{id}", method = RequestMethod.POST)
    public Map<String, Object> statusIdEdit(@PathVariable("id") Integer id, @RequestBody Map<String, String> entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        if (id == null || resumeBaseService.selectPrimaryKey(id) == null) {
            map.put("type", "error");
            map.put("message", "简历不存在");
            map.put("errors", "[]");
            return map;
        }
        Resume resume = new Resume();
        resume.setId(id);
        resume.setStatus(StringUtils.isNotBlank(entity.get("status")) ? Integer.valueOf(entity.get("status")) : null);
        resume.setTags(entity.get("tags"));
        resumeBaseService.updateByPrimaryKeySelective(resume);
        map.put("type", "success");
        map.put("message", "执行成功");
        return map;
    }

    /**
     * 批量修改简历状态
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "/resume/batchstatus", method = RequestMethod.POST)
    public Map<String, Object> batchStatusEdit(@RequestBody Map<String, String> entity) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isBlank(entity.get("status")) || StringUtils.isBlank(entity.get("ids"))) {
            map.put("type", "error");
            map.put("messages", "简历或状态不能为空");
            return map;
        }
        List<String> stringList = CommonService.splitString(entity.get("ids"), ",");
        List<Resume> list = new ArrayList<>();
        for (String domain : stringList) {
            Resume resume = new Resume();
            resume.setId(Integer.valueOf(domain));
            resume.setStatus(Integer.valueOf(entity.get("status")));
            list.add(resume);
        }
        resumeBaseService.batchUpdate(list);
        map.put("type", "success");
        map.put("message", "执行成功");
        return map;
    }

    /**
     * 工作经验保存或者更新
     *
     * @param entity
     * @return
     */
    @RequestMapping("/resume/worksave")
    public Map<String, Object> resumeWorksave(@RequestBody Map<String, String> entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        ResumeWork resumeWork = new ResumeWork();
        resumeWork.setResumeId(StringUtils.isNotBlank(entity.get("id")) ? Integer.valueOf(entity.get("id")) : null);
        resumeWork.setCompany(entity.get("company"));
        resumeWork.setPosition(entity.get("position"));
        resumeWork.setStartDate(entity.get("start_data"));
        resumeWork.setEndDate(entity.get("end_data"));
        resumeWork.setResumeId(StringUtils.isNotBlank(entity.get("resume_id")) ? Integer.valueOf(entity.get("resume_id")) : null);
        resumeWork.setDuty(entity.get("duty"));
        resumeWork.setId(StringUtils.isNotBlank(entity.get("id")) ? Integer.valueOf(entity.get("id")) : null);
        if (resumeWork.getId() == null && resumeWorkService.isExitByResumeWork(resumeWork) > 0) {
            map.put("type", "error");
            map.put("message", "你已经添加过[" + resumeWork.getCompany() + "]工作经验");
            map.put("errors", "[]");
            return map;
        }
        resumeWorkService.updateOrInsert(resumeWork);
        entity.put("id", resumeWork.getId().toString());
        map.put("type", "success");
        map.put("message", "执行成功");
        map.put("resumeWork", entity);
        return map;
    }

    /**
     * 工作经历删除
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "/resume/workdel", method = RequestMethod.POST)
    public Map<String, Object> resumeWorkDel(@RequestBody Map<String, String> entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        Integer id = Integer.valueOf(entity.get("id"));
        resumeWorkService.deleteResumeWorkById(id);
        map.put("type", "success");
        map.put("message", "执行成功");
        map.put("return", true);
        return map;
    }

    /**
     * 教育经历保存
     *
     * @param entity
     * @return
     */
    @RequestMapping("/resume/edusave")
    public Map<String, Object> resumeEdusave(@RequestBody Map<String, String> entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        ResumeEdu resumeEdu = new ResumeEdu();
        resumeEdu.setResumeId(StringUtils.isNotBlank(entity.get("id")) ? Integer.valueOf(entity.get("id")) : null);
        resumeEdu.setSchool(entity.get("school"));
        resumeEdu.setDegree(entity.get("degree"));
        resumeEdu.setStartDate(entity.get("start_data"));
        resumeEdu.setEndDate(entity.get("end_data"));
        resumeEdu.setResumeId(StringUtils.isNotBlank(entity.get("resume_id")) ? Integer.valueOf(entity.get("resume_id")) : null);
        resumeEdu.setMajor(entity.get("major"));
        resumeEdu.setId(StringUtils.isNotBlank(entity.get("id")) ? Integer.valueOf(entity.get("id")) : null);
        if (resumeEdu.getId() == null && resumeEduService.isExitResumeEdu(resumeEdu) > 0) {
            map.put("type", "error");
            map.put("message", "你已经添加过[" + resumeEdu.getSchool() + "]学校经验");
            map.put("errors", "[]");
            return map;
        }
        resumeEduService.insertOrUpdate(resumeEdu);
        entity.put("id", resumeEdu.getId().toString());
        map.put("type", "success");
        map.put("message", "执行成功");
        map.put("resumeEdu", entity);
        return map;
    }

    /**
     * 删除教育经历
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "/resume/edudel", method = RequestMethod.POST)
    public Map<String, Object> resumeEdeDel(@RequestBody Map<String, String> entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        Integer id = Integer.valueOf(entity.get("id"));
        resumeEduService.deleteResumeEduById(id);
        map.put("type", "success");
        map.put("message", "执行成功");
        map.put("return", true);
        return map;
    }

    /**
     * 工作经历保存
     *
     * @param entity
     * @return
     */
    @RequestMapping(value = "/resume/projectsave", method = RequestMethod.POST)
    public Map<String, Object> resumeProjectSave(@RequestBody Map<String, String> entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        ResumeProject resumeProject = new ResumeProject();
        resumeProject.setResumeId(StringUtils.isNotBlank(entity.get("id")) ? Integer.valueOf(entity.get("id")) : null);
        resumeProject.setProjectName(entity.get("projectname"));
        resumeProject.setDescription(entity.get("description"));
        resumeProject.setStartDate(entity.get("start_data"));
        resumeProject.setEndDate(entity.get("end_data"));
        resumeProject.setResumeId(StringUtils.isNotBlank(entity.get("resume_id")) ? Integer.valueOf(entity.get("resume_id")) : null);
        resumeProject.setDuty(entity.get("duty"));
        resumeProject.setId(StringUtils.isNotBlank(entity.get("id")) ? Integer.valueOf(entity.get("id")) : null);
        if (resumeProject.getId() == null && resumeProjectService.isExitResumeProject(resumeProject) > 0) {
            map.put("type", "error");
            map.put("message", "你已经添加过[" + resumeProject.getProjectName() + "]项目经验");
            map.put("errors", "[]");
            return map;
        }
        resumeProjectService.insertOrUpdateResumeProject(resumeProject);
        entity.put("id", resumeProject.getId().toString());
        map.put("type", "success");
        map.put("message", "执行成功");
        map.put("resumeEdu", entity);
        return map;
    }

    /**
     * 删除项目经历
     *
     * @param entity
     * @return
     */
    @RequestMapping("/resume/projectdel")
    public Map<String, Object> projectDel(@RequestBody Map<String, String> entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        Integer id = Integer.valueOf(entity.get("id"));
        resumeProjectService.deleteResumeProject(id);
        map.put("type", "success");
        map.put("message", "执行成功");
        map.put("return", true);
        return map;
    }

    @RequestMapping(value = "/resumeorig/save", method = RequestMethod.POST)
    public ApiResponse resumeorigSave(@RequestBody Map<String, String> entity) {
        ApiResponse response = new ApiResponse();
        ResumeOrig resumeOrig = new ResumeOrig();
        resumeOrig.setRealname(entity.get("realname"));
        resumeOrig.setOid(entity.get("oid"));
        resumeOrig.setSource(entity.get("source"));
        resumeOrig.setContent(entity.get("content"));
        resumeOrig.setUrl(entity.get("url"));
        resumeOrig.setStatus(StringUtils.isNotBlank(entity.get("status")) ? Integer.valueOf(entity.get("status")) : null);
        resumeOrig.setKeyword(entity.get("condition"));
        resumeOrig.setCreatetime(new Date());
        resumeOrigService.insertSelective(resumeOrig);
        response.setData("操作成功");
        return response;
    }

    @RequestMapping("/resume/deteleRepeat")
    public ApiResponse deleteRepeat() {
        //searchResumeService.batchDelete(null);
        return ApiResponse.success("批量删除成功");
    }

}
